#include "SDLCanvas.h"

namespace RTRT {
    
    int SDLCanvas :: create()
    {
        /*
        m_width = width;
        m_height = height;
        m_bytesPerPixel = bytesPerPixel;
        */
        
        // Create the pixel buffer
        m_pixelBuffer = new PixelBuffer(m_canvasCfg->getWidth(), m_canvasCfg->getHeight());
        
        if (SDL_Init(SDL_INIT_VIDEO) != 0) 
        {
            fprintf(stderr, "Unable to initialize SDL: %s\n", SDL_GetError());
            return 1;
        }

        unsigned int sdlFlag = SDL_SWSURFACE;
        //m_mainSurface = SDL_SetVideoMode(width, height, 8*m_bytesPerPixel, sdlFlag);
        m_mainSurface = SDL_SetVideoMode(m_canvasCfg->getWidth(), 
                                        m_canvasCfg->getHeight(), 
                                        m_canvasCfg->getBitsPerPixel(), 
                                        sdlFlag);
        if (NULL == m_mainSurface)
        {
            fprintf(stderr, "Unable to set video mode: %s\n", SDL_GetError());
            return 1;
        }
        return 0;
    }

    int SDLCanvas :: clean(unsigned int color)
    {
        // Clean the surface
        SDL_FillRect(m_mainSurface,NULL,color);
        SDL_UpdateRect(m_mainSurface, 0, 0, 0, 0);

        return 0;
    }

    int SDLCanvas :: display()
    {
        unsigned int rmask, gmask, bmask, amask;

        /*
#if SDL_BYTEORDER == SDL_BIG_ENDIAN
        rmask = 0xff000000;
        gmask = 0x00ff0000;
        bmask = 0x0000ff00;
        amask = 0x000000ff;
#else
        rmask = 0x000000ff;
        gmask = 0x0000ff00;
        bmask = 0x00ff0000;
        amask = 0xff000000;
#endif
         */
        rmask = 0x00ff0000;
        gmask = 0x0000ff00;
        bmask = 0x000000ff;
        amask = 0;

        SDL_Surface *pImage;
        pImage = SDL_CreateRGBSurfaceFrom((void*)(m_pixelBuffer->getPixelBuffer()),
                                        m_canvasCfg->getWidth(),
                                        m_canvasCfg->getHeight(),
                                        32,
                                        m_canvasCfg->getWidth()*4,
                                        rmask, gmask, bmask, amask);
        if (!pImage)
            return 1;

        // Clear screen surface
        // SDL_FillRect(m_mainSurface,NULL,0);

        // Blit surface
        //SDL_LockSurface(m_mainSurface);
        SDL_BlitSurface(pImage,NULL, m_mainSurface,NULL);
        //SDL_UnlockSurface(m_mainSurface);
        // Flip the surface -- DOUBLE BUFFER ONLY
        // SDL_Flip(m_mainSurface);
        SDL_UpdateRect(m_mainSurface, 0, 0, 0, 0);

        SDL_FreeSurface(pImage);
    }

    int SDLCanvas :: destroy()
    {

    }

    
}